﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.IO;
using System.Web.SessionState;
using NetWing.Model;
using NetWing.Bll;
using Omu.ValueInjecter;
using NetWing.BPM.Core;
using NetWing.BPM.Core.Bll;
using NetWing.Common;
using NetWing.Common.Data;
using NetWing.Common.Data.SqlServer;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using NetWing.Common.Excel;
using NetWing.Common.IO;
using NetWing.Common.IO.DirFile;
using NetWing.Common.Data.Filter;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using Newtonsoft.Json.Linq;
using NetWing.BPM.Core.Model;
using NetWing.BPM.Core.Dal;

namespace NetWing.BPM.Admin.mjrooms.ashx
{
    /// <summary>
    /// tuiroom 的摘要说明
    /// </summary>
    public class tuiroom : IHttpHandler
    {

        public string err = "";
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            #region 收款账号处理
            string account = "";//
            int accountid = 0;//
            decimal payment = 0;//支付总额
            //account 作为总量  accountb accountc accountd 作为子项
            int c = 1;//收款方式有几种
            string accountb = "";
            string accountidb = "0";
            string shifub = "0";

            string accountc = "";
            string accountidc = "0";
            string shifuc = "0";

            string accountd = "";
            string accountidd = "0";
            string shifud = "0";

            string accounts = context.Request["account"];//收款账号
            string accountids = context.Request["accountid"];//收款账号ID
            string shifus = context.Request["shifu"];//实付
            string[] accountarr = null;
            string[] accountidarr = null;
            string[] shifuarr = null;
            if (!string.IsNullOrEmpty(accounts))//不为空
            {
                if (accounts.IndexOf(",") > -1)//包含，说明有多个
                {
                    accountarr = accounts.Split(',');
                    accountidarr = accountids.Split(',');
                    shifuarr = shifus.Split(',');
                    c = accountidarr.Length;//计算有几个从0开始
                    switch (c)
                    {
                        case 2://2个

                            accountb = accountarr[0];
                            accountidb = accountidarr[0];
                            shifub = shifuarr[0];
                            accountc = accountarr[1];
                            accountidc = accountidarr[1];
                            shifuc = shifuarr[1];

                            account = accounts;//收款账号为多账户
                            accountid = 0;//如果多账号为0
                            payment = decimal.Parse(shifub) + decimal.Parse(shifuc);//实付金额为两个账号加起来
                            break;
                        case 3://3个
                            accountb = accountarr[0];
                            accountidb = accountidarr[0];
                            shifub = shifuarr[0];
                            accountc = accountarr[1];
                            accountidc = accountidarr[1];
                            shifuc = shifuarr[1];
                            accountd = accountarr[2];
                            accountidd = accountidarr[2];
                            shifud = shifuarr[2];

                            account = accounts;//收款账号为多账户
                            accountid = 0;//如果多账号为0
                            payment = decimal.Parse(shifub) + decimal.Parse(shifuc) + decimal.Parse(shifud);//实付金额为几个账号加起来
                            break;
                        default:
                            break;
                    }

                }
                else//说明只有一个
                {
                    account = accounts;
                    accountid = int.Parse(accountids);
                    payment = decimal.Parse(shifus);
                    //如果是一个的情况 给第一个accountb的相关值
                    accountb = account;
                    accountidb = accountid.ToString();
                    shifub = payment.ToString();


                }

            }
            #endregion
            //context.Response.Write("Hello World");
            #region 公共变量
            var main = HttpContext.Current.Request["main"];//得到主表json数据
            var detail = HttpContext.Current.Request["detail"];//得到明细表json数据
            //以后统一单号。续费的就是XF
            string edNumber = common.mjcommon.getedNumber("TZ");//得到此次财务订单号，原来是浏览器给，现在从系统获取
            var oMainObj = JSONhelper.ConvertToObject<MJOrderModel>(main);
            MJFinanceMainModel fmain = new MJFinanceMainModel();
            fmain.account = account;//账号
            fmain.accountid = accountid;//账号ID
            fmain.accountb = accountb;
            fmain.accountidb = int.Parse(accountidb);
            fmain.shifub = decimal.Parse(shifub);
            fmain.accountc = accountc;
            fmain.accountidc = int.Parse(accountidc);
            fmain.shifuc = decimal.Parse(shifuc);
            fmain.accountd = accountd;
            fmain.accountidd = int.Parse(accountidd);
            fmain.shifud = decimal.Parse(shifud);
            fmain.add_time = DateTime.Now;
            fmain.contact = oMainObj.contact;//经手人
            fmain.contactid = oMainObj.contactid;//经手人id
            fmain.dep = "";
            fmain.depid = int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
            fmain.edNumber = edNumber;
            fmain.ownner = int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
            fmain.unit = oMainObj.users;//用户
            fmain.unitid = oMainObj.usersid;//用户ID
            fmain.note = oMainObj.users + "退房收据";
            fmain.payment = payment;
            fmain.total = oMainObj.total;
            fmain.operateid = int.Parse(SysVisitor.Instance.cookiesUserId);
            fmain.operate = SysVisitor.Instance.cookiesUserName;
            fmain.roomid = oMainObj.roomid;//房间id
            fmain.roomno = oMainObj.roomno;//房间号
            fmain.orderid = oMainObj.KeyId;
            #endregion


            SqlTransaction tran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
            try
            {
                if (fmain.payment!=fmain.total)
                {
                    err = "实付金额与合计金额不符，请仔细检查！";
                    tran.Rollback();
                }


                int fmainInsertID = DbUtils.tranInsert(fmain, tran);//插入的财务主表ID
                #region 写财务明细表
                JArray detailArr = JArray.Parse(detail);//把服务明细表转化为数组
                for (int i = 0; i < detailArr.Count; i++)
                {
                    if (detailArr[i]["type"].ToString() == "原始")//如果原始订单，则只需处理财务表
                    {
                        //订单详细
                        var oDetailObj = JSONhelper.ConvertToObject<MJOrderDetailModel>(detailArr[i].ToString());
                        MJFinanceDetailModel fdetail = new MJFinanceDetailModel();
                        //fdetail.KeyId = null;//编号
                        fdetail.financeId = fmainInsertID;//主表ID
                        fdetail.ftype = null;//收支类型
                        fdetail.edNumber = edNumber;//编号
                                                    //退租的时候财务科目写对应的科目
                        fdetail.subject = detailArr[i]["tuiserviceName"].ToString();//科目
                        fdetail.subjectid = int.Parse(detailArr[i]["tuiserviceId"].ToString());//科目ID
                        fdetail.num = oDetailObj.num;//产品或服务数量
                        fdetail.sprice = oDetailObj.sprice;//单价
                        fdetail.sumMoney = decimal.Parse(detailArr[i]["tuimoney"].ToString()); ;//金额
                        fdetail.stime = oDetailObj.add_time;//服务开始时间
                        fdetail.etime = oDetailObj.exp_time;//服务到期时间
                        fdetail.dep = fmain.dep;//部门
                        fdetail.depid = fmain.depid;//部门ID
                        fdetail.note = oDetailObj.note;//备注
                        fdetail.add_time = fmain.add_time;//添加时间
                        fdetail.up_time = fmain.up_time;//更新时间
                        fdetail.ownner = oMainObj.ownner;//数据所有者ID
                        fdetail.paytype = oMainObj.paytype;//
                        fdetail.nextpaydate = oMainObj.nextpaydate;//
                        fdetail.roomid = oMainObj.roomid;//
                        fdetail.roomno = oMainObj.roomno;//
                        fdetail.userid = oMainObj.usersid;//客户ID
                        fdetail.username = oMainObj.users;//客户姓名
                        fdetail.mobile = oMainObj.mobile;//手机号
                        fdetail.contact = oMainObj.contact;//经手人
                        fdetail.contactid = oMainObj.contactid;//
                        fdetail.orderdetailid = oDetailObj.KeyId;//订单/服务明细ID
                        DbUtils.tranInsert(fdetail, tran);
                    }

                    if (detailArr[i]["type"].ToString() == "新增")
                    {
                        //订单明细单
                        int orderDetailInsertId = 0;
                        var oDetailObj = JSONhelper.ConvertToObject<MJOrderDetailModel>(detailArr[i].ToString());
                        MJOrderDetailModel oDetail = new MJOrderDetailModel();
                        //oDetail.KeyId = null;//系统编号
                        oDetail.MJOrderid = oMainObj.KeyId;//订单ID
                        oDetail.serviceName = oDetailObj.serviceName;//服务名称
                        oDetail.serviceId = oDetailObj.serviceId;//银行科目ID
                        oDetail.sprice = oDetailObj.sprice;//单价
                        oDetail.num = oDetailObj.num;//数量
                        oDetail.allprice = oDetailObj.allprice;//总价
                        oDetail.dep = fmain.dep;//部门名称
                        oDetail.depid = fmain.depid;//部门id
                        oDetail.add_time = oDetailObj.add_time;//服务开始时间
                        oDetail.exp_time = oDetailObj.exp_time;//到期时间
                        oDetail.note = oDetailObj.note;//备注
                        oDetail.ownner = fmain.ownner;//数据所有者ID
                        oDetail.contact = oMainObj.contact;//经手人
                        oDetail.contactid = oMainObj.contactid;//经手人ID
                        oDetail.users = oMainObj.users;//客户
                        oDetail.usersid = oMainObj.usersid;//用户ID
                        oDetail.roomno = oMainObj.roomno;//房间号
                        oDetail.roomid = oMainObj.roomid;//房间ID
                        oDetail.edNumber = edNumber;//系统生成的订单ID
                        //以下这两项没有意义
                        //oDetail.orderstatus = -1;//0正常-1结单
                        //oDetail.htstate = null;//是否已确定合同标识0没打1已经打了
                        oDetail.paytype = oMainObj.paytype;//
                        oDetail.nextpaydate = oMainObj.nextpaydate;//
                        orderDetailInsertId = DbUtils.tranInsert(oDetail, tran);
                        //接下来插入对应财务明细
                        MJFinanceDetailModel fdetail = new MJFinanceDetailModel();
                        //fdetail.KeyId = null;//编号
                        fdetail.financeId = fmainInsertID;//主表ID
                        fdetail.ftype = null;//收支类型
                        fdetail.edNumber = edNumber;//编号
                                                    //退租的时候如果有新增项目则填写该新增项对应的财务科目和ID
                        fdetail.subject = oDetailObj.serviceName;//科目
                        fdetail.subjectid = oDetailObj.serviceId;//科目ID
                        fdetail.num = oDetailObj.num;//产品或服务数量
                        fdetail.sprice = oDetailObj.sprice;//单价
                        fdetail.sumMoney = oDetailObj.allprice;//金额
                        fdetail.stime = oDetailObj.add_time;//服务开始时间
                        fdetail.etime = oDetailObj.exp_time;//服务到期时间
                        fdetail.dep = fmain.dep;//部门
                        fdetail.depid = fmain.depid;//部门ID
                        fdetail.note = oDetailObj.note;//备注
                        fdetail.add_time = fmain.add_time;//添加时间
                        fdetail.up_time = fmain.up_time;//更新时间
                        fdetail.ownner = oMainObj.ownner;//数据所有者ID
                        fdetail.paytype = oMainObj.paytype;//
                        fdetail.nextpaydate = oMainObj.nextpaydate;//
                        fdetail.roomid = oMainObj.roomid;//
                        fdetail.roomno = oMainObj.roomno;//
                        fdetail.userid = oMainObj.usersid;//客户ID
                        fdetail.username = oMainObj.users;//客户姓名
                        fdetail.mobile = oMainObj.mobile;//手机号
                        fdetail.contact = oMainObj.contact;//经手人
                        fdetail.contactid = oMainObj.contactid;//
                        fdetail.orderdetailid = orderDetailInsertId;//新增的时候是刚刚插入的ID
                        DbUtils.tranInsert(fdetail, tran);

                    }
                }
                #endregion

                switch (c)
                {
                    case 2://有两个收款账户的情况
                        DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance+" + shifub + " where KeyId=" + accountidb + "", tran);
                        DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance+" + shifuc + " where KeyId=" + accountidc + "", tran);
                        break;
                    case 3:
                        DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance+" + shifub + " where KeyId=" + accountidb + "", tran);
                        DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance+" + shifuc + " where KeyId=" + accountidc + "", tran);
                        DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance+" + shifud + " where KeyId=" + accountidd + "", tran);
                        break;

                    default://有一个收款账户的情况
                        DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance+" + payment + " where KeyId=" + accountid + "", tran);
                        break;
                }



                #region 结单
                //给订单主表结单 订单状态0正常-1结单
                string omainsql = "update MJOrder set orderstatus=-1,istuidate='"+DateTime.Now.ToString()+"' where keyid=" + oMainObj.KeyId + "";
                DbUtils.tranExecuteNonQuery(omainsql, tran);
                //给订单明细表结单
                string odetailsql = "update MJOrderDetail set orderstatus=-1,istuidate='" + DateTime.Now.ToString() + "'   where MJOrderid=" + oMainObj.KeyId + "";
                DbUtils.tranExecuteNonQuery(odetailsql, tran);
                //清空房间使用者信息
                //string clearroomsql = "update MJRooms set userids=null,usernames=null,usermobiles=null where roomnumber='"+dr["roomno"]+"'";
                //这里有个大漏洞，如果房间号和其他店重复的，退吧其他店的房间退掉。所以赶紧修改
                string clearroomsql = "update MJRooms set userids = null, usernames = null, usermobiles = null, state = '空闲', add_time = null, exp_time = null, orderstart_time = null, orderend_time = null, zuqi = null, jzrs = null, OrderId = null, rzl = null, paytype = null, nextpaydate = null  where keyid='" + oMainObj.roomid + "'  and depid="+SysVisitor.Instance.cookiesUserDepId+"";
                DbUtils.tranExecuteNonQuery(clearroomsql, tran);
                #endregion

                tran.Commit();//提交执行事务

                LogModel log = new LogModel();
                log.BusinessName = "退租手续办理成功";
                log.OperationIp = PublicMethod.GetClientIP();
                log.OperationTime = DateTime.Now;
                log.PrimaryKey = "";
                log.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                log.TableName = "";
                log.note = "财务主表id:" + fmainInsertID + "服务主id:" + oMainObj.KeyId + "房间号:" + oMainObj.roomno + "房间id:" + oMainObj.roomid + "客户姓名:" + oMainObj.users + "客户id:" + oMainObj.usersid;
                log.OperationType = (int)OperationType.Other;
                LogDal.Instance.Insert(log);

                context.Response.Write("{\"status\":1,\"msg\":\"办理成功，请转到业务办理处理其他业务！\"}");

            }
            catch (Exception e)
            {
                LogModel log = new LogModel();
                log.BusinessName = "退租手续办理失败";
                log.OperationIp = PublicMethod.GetClientIP();
                log.OperationTime = DateTime.Now;
                log.PrimaryKey = "";
                log.UserId = int.Parse(SysVisitor.Instance.cookiesUserId);
                log.TableName = "";
                log.note = err+e.Message;
                log.OperationType = (int)OperationType.Other;
                LogDal.Instance.Insert(log);
                //tran.Rollback();//错误！事务回滚！
                context.Response.Write("{\"status\":0,\"msg\":\"" +err+e.Message + "\"}");
                //context.Response.Write(err.ToString());
                //throw;
            }


        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}